<?php

namespace mongrove;

/**
 *
 * The IntegerField is a container for integer values.
 *
 * @author Gido Hakvoort <gido@hakvoort.it>
 * @author Michiel Hakvoort <michiel@hakvoort.it>
 *
 */
class IntegerField extends SimpleField {

    protected $minimum = null;
    protected $maximum = null;

    /**
     *
     * Define a new IntegerField
     *
     * @param int $default The default value of this field
     */
    public function __construct($default = null) {
        parent :: __construct();

        if($default !== null) {
            $this->setValue($default);
        }
    }

    /**
     * (non-PHPdoc)
     * @see src/mongrove.SimpleField::setValueImpl()
     */
    protected function setValueImpl($value) {
        if($this->value === $value) {
            return false;
        }

        $options = array();

        if($this->minimum !== null) {
            $options['options']['min_range'] = $this->minimum;
        }

        if($this->maximum !== null) {
            $options['options']['max_range'] = $this->maximum;
        }

        if(($newValue = filter_var($value, FILTER_VALIDATE_INT, $options)) === false) {
            throw new \Exception("{$value} is not a valid value for this field.");
        }

        $this->value = $newValue;

        return true;
    }

    /**
     * Set the minimum allowed value of this field. This minimum value is inclusive.
     *
     * @param int $minimum The minimum required value.
     *
     * @throws \Exception When the passed value is not an integer
     *
     * @return IntegerField
     */
    public function setMinimum($minimum) {
        if(!is_int($minimum)) {
            throw new \Exception("Minimum should be an integer value.");
        }

        $this->minimum = $minimum;

        return $this;
    }

    /**
     *
     * Set the maximum value this field can hold. This value is inclusive.
     *
     * @param int $maximum The maximum allowed value.
     *
     * @throws \Exception When the passed value is not an integer
     *
     * @return IntegerField
     */
    public function setMaximum($maximum) {
        if(!is_int($maximum)) {
            throw new \Exception("Maximum should be an integer value.");
        }

        $this->maximum = $maximum;

        return $this;
    }
}
